package com.dw.dwdzcommerce.view.mainContent.mainActionBar;

import java.math.MathContext;

import com.dw.dwdzcommerce.R;
import com.dw.dwdzcommerce.tools.commons.viewUtil.ViewUtil;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.FragmentActivity;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;

public class PopupType {

	private ViewGroup mRoot;
	private SparseArray<View> mChilds;
	private Context mContext;

	public void init(FragmentActivity activity) {
		this.mContext = activity;
		mRoot = (ViewGroup) LayoutInflater.from(mContext).inflate(R.layout.item_list_popup, null);
	}

	public void setData(String[] items) {
		mChilds = new SparseArray<View>(items.length);
		for (int i = 0; i < items.length; i++) {
			String s = items[i];
			final int tempIndex = i;
			final View tv = generateView(s);
			tv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (ppw != null && ppw.isShowing()) {
						ppw.dismiss();
					}
					if (mOnItemClickListener != null) {
						mOnItemClickListener.onItemClick(tv, tempIndex,0);
					}
				}
			});
			mChilds.append(i, tv);
			mRoot.addView(tv);
		}

	}

	private View generateView(String s) {
		TextView tv = new TextView(mContext);
		tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		tv.setText("" + s);
		tv.setPadding(5, 10, 5, 10);
		tv.setGravity(Gravity.CENTER);
		tv.setBackgroundResource(R.drawable.popup_item_bg);
		tv.setTag(s);
		return tv;
	}

	public void show(View view) {
		ppw = new PopupWindow(mRoot, Math.max(view.getMeasuredWidth()+10, ViewUtil.getScreenWidth(mContext)/9), LayoutParams.WRAP_CONTENT);
		ppw.setTouchable(true);
		ppw.setOutsideTouchable(true);
		ppw.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
		ppw.showAsDropDown(view);
	}

	private OnItemClickListener mOnItemClickListener;
	private PopupWindow ppw;

	public void setmOnItemClickListener(OnItemClickListener mOnItemClickListener) {
		this.mOnItemClickListener = mOnItemClickListener;
	}

	public interface OnItemClickListener {
		void onItemClick(View view, int pos,int arg0);
	}

}
